<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1,maximum-scale=1.0, user-scalable=no">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css">
  <title>Wechat JSSDK DEMO</title>
  <!--<script src="./client.js"></script>-->
</head>
<body class="container pt-3">
  <h5>=====点击右上角分享!=====</h5>
  <h5>=====OAuth 网页授权=====</h5>
  <p><a id="oauth-1" href="{{ oauthUrl }}">OAuth 用户信息授权</a></p>
  <p><a id="oauth-2" href="{{ implicitOAuth }}">Implicit OAuth 静默授权</a></p>
  <p><a id="oauth-3" href="/oauth-cache">OAuth without new code 用缓存code直接拿用户信息</a></p>
  <h5>=====CARD 卡券=====</h5>
  <p><a id="choose-card" href="#">ChooseCard 选择卡券并打开</a></p>
  <p><a id="open-card" href="#">OpenCard 打开卡券</a></p>
  <p><a id="add-card" href="#">AddCard 添加卡券</a></p>
  <h5>=====Payment 支付=====</h5>
  <div class="d-flex justify-content-between">
    <input class="form-control mr-2" id="order-id" name="orderId" placeholder="输入out_trade_no"/>
    <button class="btn btn-primary" onclick="queryOrder()">查询订单</button>
  </div>
  <p><a id="query-order" href="#">QueryOrder 查询上一个创建的订单</a></p>
  <p><a class="create-order" data-case="1" href="#">UnifiedOrder 创建订单用例1</a></p>
  <p><a class="create-order create-order-2" data-case="2" href="#">UnifiedOrder 创建订单用例2</a></p>
  <p><a class="create-order create-order-3" data-case="3" href="#">UnifiedOrder 创建订单用例3</a></p>
  <p><a class="create-order create-order-4" data-case="4" href="#">UnifiedOrder 创建订单用例4</a></p>
  <p><a class="create-order create-order-5" data-case="5" href="#">UnifiedOrder 创建订单用例5</a></p>
  <p><a class="create-order create-order-6" data-case="6" href="#">UnifiedOrder 创建订单用例6</a></p>
  <p><a class="create-order create-order-7" data-case="7" href="#">UnifiedOrder 创建订单用例7</a></p>
  <p><a class="create-order create-order-8" data-case="8" href="#">UnifiedOrder 创建订单用例8(可选)</a></p>
  <p><a id="download-order" href="#">下载对账单</a></p>
  <p><a id="pay-now" href="#">chooseWXPay 微信支付上一个订单</a></p>
  <script type="text/javascript">
    const config = {
      debug: true
    };
    
    //default wechat script url
let defaultScriptUrl = '//res.wx.qq.com/open/js/jweixin-1.4.0.js';

//default apis with share-on-moment and share-on-chat
const defaultApiList = ['onMenuShareTimeline', 'onMenuShareAppMessage'];

class WechatJSSDK {
  constructor(wechatConfig) {
    //using new WechatJSSDK(config);
    if (this instanceof WechatJSSDK) {
      this.sdkUrl = defaultScriptUrl;
      this.config = wechatConfig || {};
      if (this.config.customUrl) {
        this.sdkUrl = this.config.customUrl;
      }
      let apiList = this.config.jsApiList;
      //add more apis if passed in
      if (!apiList || apiList.length <= 0) {
        this.config.jsApiList = defaultApiList;
      } else {
        let i = 0;
        const length = defaultApiList.length;
        for (; i < length; i++) {
          const defaultItem = defaultApiList[i];
          if (apiList.indexOf(defaultItem) < 0) {
            apiList.push(defaultItem);
          }
        }
      }
      this.debug = !!this.config.debug;
      return this;
    }
    return new WechatJSSDK(wechatConfig);
  }
  initialize() {
    return this.loadScript();
  }
  signSignature(newSignConfig) {
    const selfConfig = this.config;
    const config = newSignConfig || selfConfig;
    const signConfig = {
      debug: this.debug,
      appId: selfConfig.appId,
      timestamp: config.timestamp || selfConfig.timestamp,
      nonceStr: config.nonceStr || selfConfig.nonceStr,
      signature: config.signature || selfConfig.signature,
      jsApiList: selfConfig.jsApiList.slice(0, selfConfig.jsApiList.length),
    };
    const debug = this.debug;
    return new Promise((resolve, reject) => {
      if (!window.wx) {
        return reject(new Error('wx js not defined'));
      }
      const wx = window.wx;
      //export original wx object
      this.setOriginWx();
      wx.config(signConfig);
      wx.ready(() => {
        console.log('sign signature finished...');
        this.setOriginWx();
        resolve(this);
      });
      wx.error(err => {
        debug && alert('sign error: ' + JSON.stringify(err));
        this.setOriginWx();
        reject(err);
      });
    });
  }
  loadScript() {
    return new Promise((resolve, reject) => {
      const ele = document.createElement('script');
      ele.type = 'text/javascript';
      ele.async = true;
      ele.onload = () => {
        console.log('Wechat script loaded successfully!');
        //init the wechat config
        this.signSignature()
          .then(instance => {
            resolve(instance);
          })
          .catch(err => {
            reject(err);
          });
      };
      ele.onerror = err => {
        console.error('Failed to load wechat script!');
        console.error(err);
        this.debug && alert('Cannot load wechat script!');
        reject(err);
      };
      const linkEle = document.getElementsByTagName('script')[0];
      linkEle.parentNode.insertBefore(ele, linkEle);
      ele.src = this.sdkUrl;
    });
  }
  shareOnMoment(info) {
    if (!info) return this;
    return this.callWechatApi('onMenuShareTimeline', info);
  }
  shareOnChat(info) {
    if (!info) return this;
    return this.callWechatApi('onMenuShareAppMessage', info);
  }
  callWechatApi(apiName, config, cb) {
    if (!apiName) return this;
    const debug = this.debug;
    if (this.config.jsApiList.indexOf(apiName) < 0) {
      debug &&
        alert(
          'the wechat api [' +
            apiName +
            '] you call was not registered, \npls add the api into your [jsApiList] config'
        );
      return this;
    }
    const wx = this.getOriginalWx();
    console.log(wx,"wx")
    let customAPI = wx[apiName]
    console.log(customAPI,"customAPI")
    if (!customAPI || 'function' !== typeof customAPI) {
      debug && alert('no such api [' + apiName + '] found!');
      return this;
    }
    console.log(config,"config")
    console.log(cb,"cb")
    customAPI(config, cb);
    return this;
  }
  getOriginalWx() {
    return this.wx || window.wx;
  }
  setOriginWx() {
    if (!this.wx) {
      this.wx = window.wx;
    }
    return this;
  }
}
    
    
    
    
    
    
    
    
    
    const demoCardId = 'pe0PN5sOI703esi9tL1RIIllaA7w';

    window.fetch(`/get-signature?url=${encodeURIComponent(location.href)}`, {
        credentials: "same-origin",
      })
      .then(res => res.json())
      .then(data => {
        console.log(data,"data")
        config.appId = data.appId;
        config.nonceStr = data.nonceStr;
        config.signature = data.signature;
        config.timestamp = data.timestamp;
        config.jsApiList = [
          'hideMenuItems',
          'onMenuShareTimeline',
          'chooseCard',
          'addCard',
          'openCard',
          'chooseWXPay',
          // 'updateAppMessageShareData',
          // 'updateTimelineShareData',
        ];
        window.wechatObj = new WechatJSSDK(config);
        window.wechatObj.initialize()
          .then(w => {
            //w is same as window.wechatObj
            console.log('success');
            const img = 'https://blog.lovemily.me/static/logo-f388230cfb3bedce8e193de215a3ef88.jpg';
            //sugar method
            window.wechatObj.shareOnMoment({
              title: 'onMenuShareTimeline test title',
              type: 'link',
              success: function () {
                console.log('share on moment success');
              },
              cancel: function () {
                console.log('share on moment canceled');
              },
              imgUrl: img
            });
            w.callWechatApi('onMenuShareAppMessage', {
              title: 'onMenuShareAppMessage test title',
              type: 'link',
              desc: 'onMenuShareAppMessage share description',
              success: function () {
                console.log('share on chat success');
              },
              cancel: function () {
                console.log('share on chat canceled');
              },
              imgUrl: img
            });

            //v1.4.0 new api
            // w.callWechatApi('updateTimelineShareData', {
            //   title: 'updateTimelineShareData test title',
            //   type: 'link',
            //   imgUrl: img
            // }, res => {
            //   console.log('updateTimelineShareData callback: ', res);
            // });
            // w.callWechatApi('updateTimelineShareData', {
            //   title: 'updateTimelineShareData test title',
            //   type: 'link',
            //   desc: 'updateTimelineShareData share description',
            //   imgUrl: img
            // }, res => {
            //   console.log('updateTimelineShareData callback: ', res);
            // });
          })
          .catch(err => {
            console.log(err,"err出错");
          })
      });

    document.getElementById('choose-card').addEventListener('click', (e) => {
      e.preventDefault();
      window.fetch(`/choose-card?cardId=${demoCardId}`, {
          credentials: "same-origin",
        })
        .then(res => res.json())
        .then(data => {
          window.wechatObj.callWechatApi('chooseCard', Object.assign(data, {
            success: res => {
              console.log(res.cardList);
              const list = JSON.parse(res.cardList);
              //open the selected card
              window.fetch(`/decode-card-code?encryptCode=${list[0].encrypt_code}`)
                .then(res => res.json())
                .then(data => {
                  window.wechatObj.callWechatApi('openCard', {
                    cardList: [{
                      cardId: demoCardId,
                      code: data.code,
                    }],
                  })
                });
            }
          }));
        });
    }, false);

    document.getElementById('open-card').addEventListener('click', (e) => {
      e.preventDefault();
      window.wechatObj.callWechatApi('openCard', {
        cardList: [{
          cardId: demoCardId,
          code: '815153541008',
        }],
      })
    }, false);

    document.getElementById('add-card').addEventListener('click', (e) => {
      e.preventDefault();
      window.fetch(`/get-card-ext?cardId=${demoCardId}`, {
          credentials: "same-origin",
        })
        .then(res => res.json())
        .then(data => {
          window.wechatObj.callWechatApi('addCard', {
            cardList: [{
              cardId: demoCardId,
              cardExt: data.data,
            }],
            success: function (res) {
              const cardList = res.cardList; // 添加的卡券列表信息
              console.log(typeof cardList, cardList);
            }
          })
        });

    }, false);

    let wxData = {};
    Array.from(document.querySelectorAll('.create-order'))
      .forEach(ele => {
        ele.addEventListener('click', (e) => {
          console.log(e.target.dataset.case,"eeeeeeeeeeeeeee")
          e.preventDefault();
          window.fetch(`/create-order?case=${e.target.dataset.case}`, {
              credentials: "same-origin",
            })
            .then(res => res.json())
            .then(data => {
              wxData = data;
              alert(JSON.stringify(data));
              // window.wechatObj.callWechatApi('chooseWXPay', Object.assign({
              //   success: res => {
              //     console.log(res);
              //   }
              // }, data));
            });

        }, false);
      });

    document.getElementById('query-order').addEventListener('click', (e) => {
      e.preventDefault();
      window.fetch(`/query-order`, {
          credentials: "same-origin",
        })
        .then(res => res.json())
        .then(data => {
          console.log(data);
          alert(JSON.stringify(data));
        });

    }, false);

    document.getElementById('download-order').addEventListener('click', (e) => {
      e.preventDefault();
      const date = new Date;
      date.setDate(date.getDate() - 1);
      const d = `${date.getFullYear()}${pad(date.getMonth() + 1)}${pad(date.getDate())}`;
      location.href = `/download-bill?billDate=${d}`;
    }, false);

    document.getElementById('pay-now').addEventListener('click', (e) => {
        console.log("11111111111111111111111")
      e.preventDefault();
      console.log(wxData,"wxData")
      console.log(Object.assign,"哈哈哈")
      window.wechatObj.callWechatApi('chooseWXPay', Object.assign({
        success: res => {
          console.log(res);
        }
      }, wxData));

    }, false);

    const input = document.getElementById('order-id');
    console.log(input,"input")
    function queryOrder() {
      window.fetch(`/query-order?tradeNo=${input.value}`, {
          credentials: "same-origin",
        })
        .then(res => res.json())
        .then(data => {
          console.log(data,"data111111111");
          alert(JSON.stringify(data));
        });
    }

    function pad(input) {
      return input >= 10 ? input : `0${input}`;
    }
  </script>
</body>
</html>
